<template>
  <el-dialog
    v-model="dialogFormVisible"
    :close-on-click-modal="false"
    :title="title"
    width="60%"
    @close="close"
  >
    <el-row :gutter="20">
      <el-col :lg="5" :md="5" :sm="24" :xl="5" :xs="24">
        <vab-card class="left-height">
          <div
            v-for="(item, index) in weekList"
            :key="index"
            :class="
              weekIndex == index ? 'week-card select' : 'week-card no-select'
            "
            @click="weekCard(item, index)"
          >
            <el-row justify="space-between">
              <div class="week-content">{{ item.label }}</div>
              <div v-if="item.isDay == 1" class="week-sign">
                <div class="sign-day">今天</div>
              </div>
            </el-row>
          </div>
        </vab-card>
      </el-col>
      <el-col :lg="9" :md="9" :sm="24" :xl="9" :xs="24">
        <vab-card class="left-height">
          <el-button
            :icon="Plus"
            style="margin-bottom: 10px; margin-right: 20px"
            type="primary"
            @click="addMsg"
          >
            添加消息
          </el-button>
          <el-radio-group
            v-model="requestBody.chat_type"
            style="margin-bottom: 10px"
            @change="radioChange($event)"
          >
            <el-radio key="single" label="single">发送客户</el-radio>
            <el-radio key="group" label="group">发送客户群</el-radio>
          </el-radio-group>
          <vab-card>
            <template #header>
              <el-row justify="space-between">
                <div>
                  <span style="font-weight: bold">文本消息</span>
                  <span style="font-size: 12px">(只能发一条)</span>
                </div>
                <el-button class="but_text" type="success" @click="updateTitle">
                  <vab-icon icon="edit-box-line" style="margin: 0 !important" />
                </el-button>
              </el-row>
            </template>
            {{ requestBody.content }}
          </vab-card>
          <div
            v-for="(item, index) in requestBody.attachments"
            :key="index"
            :class="
              clickIndex == index ? 'div-card select' : 'div-card no-select'
            "
            @click="editCard(item, index)"
          >
            <div class="card-del">
              <!-- <el-button
                class="but_text"
                type="success"
                @click="editCard(item, index)"
              >
                <vab-icon icon="edit-box-line" style="margin: 0 !important" />
              </el-button> -->
              <el-button
                class="but_text"
                type="danger"
                @click.stop="delCard(index)"
              >
                <vab-icon
                  icon="delete-bin-7-line"
                  style="margin: 0 !important"
                />
              </el-button>
            </div>
            <div v-if="item.msgtype">
              <div
                v-if="item.msgtype == 'link' || item.msgtype == 'miniprogram'"
                class="card-title"
              >
                {{
                  item.msgtype == 'link'
                    ? item.link.title
                    : item.miniprogram.title
                }}
              </div>
              <div class="card-content">
                <div v-if="item.msgtype == 'link'" class="card-desc">
                  {{ item.link.desc }}
                </div>
                <vab-icon
                  v-if="item.msgtype == 'miniprogram'"
                  icon="mini-program-line"
                  style="color: #1890ff; font-size: 30px; margin-top: 15px"
                />
                <div class="demo-image">
                  <el-image
                    :lazy="true"
                    preview-teleported
                    :src="
                      item.msgtype == 'link'
                        ? item.link.picurl
                        : item.msgtype == 'miniprogram'
                        ? item.miniprogram.pic_url
                        : item.image.pic_url
                    "
                  />
                </div>
              </div>
            </div>
          </div>
        </vab-card>
      </el-col>
      <el-col :lg="10" :md="10" :sm="24" :xl="10" :xs="24">
        <vab-card>
          <div class="card-tips">注：添加或修改完后，请先点击保存按钮</div>
          <el-form
            ref="formRef"
            label-width="100px"
            :model="form"
            :rules="rules"
          >
            <div>
              <el-form-item label="消息类型：" prop="msg_type">
                <el-select
                  v-model="form.msg_type"
                  placeholder="请选择消息类型"
                  style="flex-grow: 1"
                  @change="selectChanged"
                >
                  <el-option
                    v-for="item in weComType"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                v-if="form.msg_type == 'text'"
                label="文本消息："
                prop="text"
              >
                <el-input
                  v-model.trim="form.text"
                  placeholder="请输入文本消息内容"
                  rows="8"
                  type="textarea"
                />
              </el-form-item>
              <el-form-item
                v-if="form.msg_type == 'miniprogram'"
                label="APPID："
                prop="appid"
              >
                <el-input
                  v-model.trim="form.appid"
                  placeholder="请输入小程序APPID"
                />
              </el-form-item>
              <el-form-item
                v-if="form.msg_type == 'link' || form.msg_type == 'miniprogram'"
                label="推送标题："
                prop="title"
              >
                <el-input
                  v-model.trim="form.title"
                  placeholder="请输入推送标题"
                />
              </el-form-item>
              <el-form-item
                v-if="form.msg_type == 'link'"
                label="推送描述："
                prop="desc"
              >
                <el-input
                  v-model.trim="form.desc"
                  placeholder="请输入推送描述"
                  rows="4"
                  type="textarea"
                />
              </el-form-item>
              <el-form-item
                v-if="form.msg_type == 'link' || form.msg_type == 'miniprogram'"
                label="跳转链接："
                prop="url"
              >
                <el-input
                  v-model.trim="form.url"
                  placeholder="请输入跳转链接"
                />
              </el-form-item>
              <el-form-item
                v-if="
                  form.msg_type == 'image' ||
                  form.msg_type == 'link' ||
                  form.msg_type == 'miniprogram'
                "
                label="素材："
                prop="media_id"
              >
                <div class="file_pot">
                  <el-upload
                    ref="upload"
                    accept="image/jpeg,image/gif,image/png"
                    :action="action"
                    :auto-upload="false"
                    :class="[
                      'upload-content',
                      fileList.length == 0 ? 'upload_show' : 'upload_hide',
                    ]"
                    :file-list="fileList"
                    :limit="limit"
                    :list-type="picture"
                    :multiple="true"
                    :on-change="handleChange"
                    :on-exceed="handleExceed"
                    :on-preview="handlePreview"
                    :on-remove="handleRemove"
                  >
                    <template #trigger v-if="fileList.length == 0">
                      <vab-icon class="avatar-uploader-icon" icon="add-line" />
                    </template>
                    <el-dialog
                      v-model="dialogVisible"
                      append-to-body
                      title="查看大图"
                    >
                      <div class="upload-image">
                        <el-image :src="dialogImageUrl" />
                      </div>
                    </el-dialog>
                  </el-upload>
                </div>
              </el-form-item>
            </div>
          </el-form>
          <el-row justify="end">
            <el-button type="primary" @click="saveMsg">保存</el-button>
          </el-row>
        </vab-card>
      </el-col>
    </el-row>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">发 送</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import {
    chatAddMsg,
    chatMsgList,
    chatSaveMsg,
  } from '@/api/enterpriseWeChat/customer'
  import {
    uploadWeCom,
    getWeComMedia,
    getWeComType,
  } from '@/api/enterpriseWeChat/weCom'
  import { uploadImage } from '@/api/file'
  import { Plus } from '@element-plus/icons-vue'
  export default defineComponent({
    name: 'TableEdit',
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const $baseMessage = inject('$baseMessage')
      const state = reactive({
        formRef: null,
        treeRef: null,
        form: {
          msg_type: 'link',
          text: '',
          title: '',
          desc: '',
          url: '',
          media_id: '',
          picurl: '',
          appid: '',
        },
        rules: {
          msg_type: [
            { required: true, trigger: 'blur', message: '请选择消息类型' },
          ],
          appid: [{ required: true, trigger: 'blur', message: '请输入APPID' }],
          text: [
            { required: true, trigger: 'blur', message: '请输入文本消息内容' },
          ],
          title: [
            { required: true, trigger: 'blur', message: '请输入推送标题' },
          ],
          desc: [
            { required: true, trigger: 'blur', message: '请输入推送描述' },
          ],
          url: [{ required: true, trigger: 'blur', message: '请输入跳转链接' }],
          media_id: [
            { required: true, trigger: 'blur', message: '请上传素材' },
          ],
        },
        list: [],
        weekList: [
          { id: 1, label: '周一', isDay: 0 },
          { id: 2, label: '周二', isDay: 0 },
          { id: 3, label: '周三', isDay: 0 },
          { id: 4, label: '周四', isDay: 0 },
          { id: 5, label: '周五', isDay: 0 },
          { id: 6, label: '周六', isDay: 0 },
          { id: 7, label: '周日', isDay: 0 },
        ],
        weComType: [],
        fileList: [],
        msgList: [],
        dialogImageUrl: [],
        listLoading: false,
        title: '',
        limit: 1,
        size: 1,
        picture: 'picture',
        action: '',
        week: null,
        clickIndex: null,
        weekIndex: null,
        dialogVisible: false,
        dialogFormVisible: false,
        weekNow: null,
        requestBody: {
          id: null,
          corp_id: '',
          user_id: '',
          week: null,
          chat_type: 'single',
          content: '',
          attachments: [],
        },
      })

      const showEdit = async (row) => {
        console.log(row)
        state.title = '发送消息'
        state.form.msg_type = 'link'
        state.dialogFormVisible = true
        state.weekNow = getCurrentWeekday()
        state.requestBody.corp_id = row.corp_id
        state.requestBody.user_id = row.user_id
        state.requestBody.chat_type = 'single'
        await getCustomer(row)
        const dateNow = state.weekList.find((ite) => ite.id == state.weekNow.id)
        dateNow.isDay = 1
        state.week = dateNow.id
        state.requestBody.week = state.week
        weekCard(dateNow, dateNow.id - 1)
        console.log(dateNow)
      }
      const handlePreview = (file) => {
        console.log(file)
        state.dialogImageUrl = file.url
        state.dialogVisible = true
      }
      const handleChange = (file) => {
        if (file.size > 1048576 * state.size) {
          $baseMessage('图片不能超过1MB', 'error', 'vab-hey-error-success')
          state.fileList = []
        } else {
          const formData = new FormData()
          formData.append('corp_id', state.requestBody.corp_id)
          formData.append('file', file.raw)
          if (state.form.msg_type == 'link') {
            uploadImageData(formData)
          } else {
            uploadData(formData)
          }
        }
      }
      const handleExceed = () => {
        $baseMessage('每次只能上传一张哦', 'error', 'vab-hey-error-success')
      }
      const handleRemove = () => {
        state.fileList = []
        state.form.media_id = ''
        $baseMessage('移除成功', 'success', 'vab-hey-message-success')
      }
      const uploadData = async (file) => {
        state.fileList.push({ url: '', name: '查看详情' })
        const { code, message, data } = await uploadWeCom(file)
        if (code == 200) {
          state.form.media_id = data.media_id
        } else {
          state.fileList = []
        }
        $baseMessage(message, 'success', 'vab-hey-message-success')
      }
      const uploadImageData = async (file) => {
        state.fileList.push({ url: '', name: '查看详情' })
        const { code, message, data } = await uploadImage(file)
        if (code == 200) {
          state.form.media_id = data.url
          state.form.picurl = data.url
          if (data.errcode == 0) {
            $baseMessage('上传图片成功', 'success', 'vab-hey-message-success')
          } else {
            $baseMessage(message, 'error', 'vab-hey-message-error')
          }
        } else {
          state.fileList = []
        }
      }
      const close = () => {
        state['formRef'].resetFields()
        state.form = {}
        state.fileList = []
        state.week = null
        state.weekIndex = null
        state.clickIndex = null
        state.requestBody = {
          id: null,
          corp_id: '',
          user_id: '',
          chat_type: 'single',
          content: '',
          week: null,
          attachments: [],
        }
        state.dialogFormVisible = false
      }
      const addMsg = () => {
        if (state.requestBody.attachments.length < 9) {
          state.form = {}
          state.fileList = []
          state.form.msg_type = 'link'
          state.requestBody.attachments.push({})
          state.clickIndex = state.requestBody.attachments.length - 1
        } else {
          $baseMessage('最多追加9条消息', 'error', 'vab-hey-message-error')
        }
      }
      const saveMsg = () => {
        state['formRef'].validate(async (valid) => {
          if (valid) {
            if (state.clickIndex != null) {
              await getUpdateMsg()
            } else {
              await getAddMsg()
            }
            state.requestBody.week = state.week
            const { code, message } = await chatSaveMsg(state.requestBody)
            if (code == 200) {
              await getCustomer(state.requestBody)
              $baseMessage(message, 'success', 'vab-hey-message-success')
            }
          }
        })
      }
      const getAddMsg = async () => {
        if (state.form.msg_type == 'text') {
          state.clickIndex = null
          state.requestBody.content = state.form.text
          return
        }
        if (state.requestBody.attachments.length < 9) {
          if (state.form.msg_type == 'image') {
            const data = await getWeComMediaData(state.form.media_id)
            state.requestBody.attachments.push({
              msgtype: 'image',
              image: {
                media_id: state.form.media_id,
                pic_url: data.url,
              },
            })
          } else if (state.form.msg_type == 'link') {
            state.requestBody.attachments.push({
              msgtype: 'link',
              link: {
                title: state.form.title,
                desc: state.form.desc,
                url: state.form.url,
                picurl: state.form.picurl,
              },
            })
          } else if (state.form.msg_type == 'miniprogram') {
            const data = await getWeComMediaData(state.form.media_id)
            state.requestBody.attachments.push({
              msgtype: 'miniprogram',
              miniprogram: {
                title: state.form.title,
                pic_media_id: state.form.media_id,
                pic_url: data.url,
                appid: state.form.appid,
                page: state.form.url,
              },
            })
          }
        } else {
          $baseMessage('最多追加9条消息', 'error', 'vab-hey-message-error')
        }
      }
      const getUpdateMsg = async () => {
        if (state.form.msg_type == 'text') {
          state.clickIndex = null
          state.requestBody.content = state.form.text
          return
        }
        if (state.form.msg_type == 'image') {
          const data = await getWeComMediaData(state.form.media_id)
          state.requestBody.attachments[state.clickIndex] = {
            msgtype: 'image',
            image: {
              media_id: state.form.media_id,
              pic_url: data.url,
            },
          }
        } else if (state.form.msg_type == 'link') {
          state.requestBody.attachments[state.clickIndex] = {
            msgtype: 'link',
            link: {
              title: state.form.title,
              desc: state.form.desc,
              url: state.form.url,
              picurl: state.form.picurl,
            },
          }
        } else if (state.form.msg_type == 'miniprogram') {
          const data = await getWeComMediaData(state.form.media_id)
          state.requestBody.attachments[state.clickIndex] = {
            msgtype: 'miniprogram',
            miniprogram: {
              title: state.form.title,
              pic_media_id: state.form.media_id,
              pic_url: data.url,
              appid: state.form.appid,
              page: state.form.url,
            },
          }
        }
      }
      const getWeComMediaData = async (media_id) => {
        const { data } = await getWeComMedia({
          corp_id: state.requestBody.corp_id,
          media_id: media_id,
        })
        return data
      }
      const selectChanged = () => {
        state.fileList = []
        state.dialogImageUrl = []
      }
      const save = async () => {
        console.log(state.requestBody)
        state.requestBody.week = state.week
        const { code, message } = await chatAddMsg(state.requestBody)
        if (code == 200) {
          close()
          $baseMessage(message, 'success', 'vab-hey-message-success')
        }
      }
      const radioChange = async (e) => {
        state.clickIndex = null
        state.form.msg_type = 'link'
        state.requestBody = {
          id: null,
          corp_id: state.requestBody.corp_id,
          user_id: state.requestBody.user_id,
          chat_type: e,
          content: '',
          week: state.week,
          attachments: [],
        }
        const msgData = state.msgList.find((ite) => ite[0].week == state.week)
        if (msgData) {
          msgMap(e, msgData)
        }
      }
      const msgMap = (e, msgData) => {
        msgData.map((item) => {
          if (item.chat_type == e) {
            state.requestBody.id = item.id
            state.requestBody.corp_id = item.corp_id
            state.requestBody.user_id = item.user_id
            state.requestBody.chat_type = item.chat_type
            state.requestBody.content = item.content
            state.requestBody.attachments = JSON.parse(item.attachments)
          }
        })
        state.requestBody.week = state.week
      }
      const weekCard = (item, index) => {
        if (state.weekIndex != index) {
          state.weekIndex = index
          state.clickIndex = null
          state.form = {}
          state.fileList = []
          state.week = item.id
          radioChange('single')
        }
      }
      const editCard = (item, index) => {
        state.fileList = []
        state.clickIndex = index
        state.form.msg_type = item.msgtype
        if (item.msgtype == 'image') {
          state.form.media_id = item.image.media_id
          state.form.picurl = item.image.pic_url
        } else if (item.msgtype == 'link') {
          state.form.title = item.link.title
          state.form.desc = item.link.desc
          state.form.media_id = item.link.picurl
          state.form.picurl = item.link.picurl
          state.form.url = item.link.url
        } else if (item.msgtype == 'miniprogram') {
          state.form.title = item.miniprogram.title
          state.form.appid = item.miniprogram.appid
          state.form.page = item.miniprogram.url
          state.form.media_id = item.miniprogram.pic_media_id
          state.form.picurl = item.miniprogram.pic_url
        }
        state.fileList.push({
          url: state.form.picurl,
          name: '查看详情',
        })
      }
      const getWeComTypeData = async () => {
        const { data } = await getWeComType()
        state.weComType = data
      }
      const getCustomer = async (row) => {
        const { data } = await chatMsgList({
          corp_id: row.corp_id,
          user_id: row.user_id,
        })
        console.log(state.form)
        state.msgList = data
      }
      const delCard = async (data) => {
        console.log(data)
        state.requestBody.attachments.splice(data, 1)
        const { code, message } = await chatSaveMsg(state.requestBody)
        if (code == 200) {
          state.clickIndex = null
          await getCustomer(state.requestBody)
          $baseMessage(message, 'success', 'vab-hey-message-success')
        }
      }
      const updateTitle = async () => {
        state.clickIndex = null
        state.form = {}
        state.fileList = []
        state.form.msg_type = 'text'
        state.form.text = state.requestBody.content
      }

      const getCurrentWeekday = () => {
        const weekdays = [
          { id: 7, label: '周日' },
          { id: 1, label: '周一' },
          { id: 2, label: '周二' },
          { id: 3, label: '周三' },
          { id: 4, label: '周四' },
          { id: 5, label: '周五' },
          { id: 6, label: '周六' },
        ]
        const today = new Date()
        const weekday = today.getDay()
        return weekdays[weekday]
      }
      onMounted(() => {
        getWeComTypeData()
      })
      return {
        ...toRefs(state),
        Plus,
        showEdit,
        close,
        save,
        saveMsg,
        addMsg,
        handleChange,
        handlePreview,
        handleExceed,
        handleRemove,
        selectChanged,
        weekCard,
        editCard,
        delCard,
        updateTitle,
        radioChange,
      }
    },
  })
</script>

<style lang="scss" scoped>
  .card-tips {
    font-size: 12px;
    margin-bottom: 10px;
    color: red;
  }
  .demo-image {
    display: flex;
    align-items: center;
    justify-content: center;
    .el-image {
      height: 100%;
    }
  }
  .week-content {
    display: flex;
    align-items: center;
  }
  .week-sign {
    width: 26px;
    height: 26px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 50%;
    background-color: #67c23a;
    .sign-day {
      font-size: 10px;
      color: #fff;
    }
  }
  .left-height {
    height: 500px;
    overflow-y: auto;
    .but_text {
      width: 18px;
      height: 18px;
      font-size: 11px;
    }
  }
  .div-card {
    min-height: 50px;
  }
  .div-card,
  .week-card {
    position: relative;
    padding: 10px;
    border: 1px solid var(--el-card-border-color);
    border-radius: 2px;
    margin-bottom: 10px;
    .card-del {
      position: absolute;
      right: 0px;
      top: 0px;
      cursor: pointer;
    }
    .card-title {
      font-size: 16px;
      text-align: left;
    }
    .card-content {
      height: 50px;
      display: flex;
      justify-content: space-between;
    }
    .card-desc {
      text-align: left;
      margin-top: 5px;
      color: #b2b2b2;
    }
  }
  .select {
    background-color: #e8f4ff;
  }
  .no-select {
    background-color: #fff;
  }
  .vab-card {
    position: relative;
  }
  :deep() {
    .el-card__body {
      padding: 10px 15px !important;
    }
    .el-card__header {
      padding: 5px !important;
    }
    .el-card {
      margin-bottom: 10px !important;
    }
  }
</style>
